"""
-------------------------------------------------
   File Name：     test01
   Description :   实体类试验--
   Author :       DuanZhangjie
   date：         2021-12-23 20:06
-------------------------------------------------
"""
import datetime
from sqlalchemy import Column, Integer, String, DateTime, UniqueConstraint, Index
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import scoped_session

Base = declarative_base()
engine = create_engine(
    "mysql+pymysql://connUser:123a123@127.0.0.1:3306/djangotest?charset=utf8",
    max_overflow=0,
    pool_size=5,
    pool_timeout=30,
    # pool_recyle=-1
)


# 定义一个装饰器，可以将一些增加的实体类功能在这里实现
def entity_base(cls):
    cls.__fields__ = set()

    def get_fields(self):
        if cls.__tablename__ is None:
            return None
        if not cls.__fields__:
            session = scoped_session(sessionmaker(bind=engine))
            sql_mysql_fields = f'''
                                SELECT COLUMN_NAME
                                FROM
                                    information_schema.COLUMNS
                                WHERE
                                    TABLE_SCHEMA = '{engine.url.database}'
                                AND TABLE_NAME = '{cls.__tablename__}'
                                '''
            cursor = session.execute(sql_mysql_fields)
            fields = cursor.fetchall()
            for f in fields:
                cls.__fields__.add(f[0])
            session.commit()
            session.close()
            print('初始化fields----------')
        return cls.__fields__

    # 这句是对装饰器对象增加这个方法
    cls.get_fields = get_fields
    # 这句是装饰器最后必写的
    return cls


@entity_base
class Test01(Base):
    __tablename__ = 'test01'
    id = Column(Integer, primary_key=True)
    # name = Column(String(32), index=True, nullable=False)
    name = Column(String(32), nullable=False)
    age = Column(Integer, nullable=False)
    phone = Column(String(11))
    addr = Column(String(64), nullable=True)
    create_time = Column(DateTime, default=datetime.datetime.now)


@entity_base
class UsersTest(Base):
    __tablename__ = 'userstest'
    id = Column(Integer, primary_key=True)
    # name = Column(String(32), index=True, nullable=False)
    name = Column(String(32), nullable=False)
    age = Column(Integer, nullable=False)
    phone = Column(String(11))
    addr = Column(String(64), nullable=True)
    create_time = Column(DateTime, default=datetime.datetime.now)

    # __table_args__ = (
    #     UniqueConstraint('id', 'name'),
    #     Index('phone', 'addr', unique=True)
    # )

    def __str__(self):
        return f'object:<id:{self.id} name:{self.name}>'


def creat_tb():
    # Base.metadata.create_all(engine)
    pass


def drop_tb():
    pass
    # Base.metadata.drop_all(engine)


if __name__ == '__main__':
    # drop_tb()
    # creat_tb()
    a = Test01()
    print(a.get_fields())
    print(a.__fields__)
    b = Test01()
    print(b.get_fields())
    print(b.__fields__)
    for f in b.__fields__:
        print(f)
    c=UsersTest()
    print(c.get_fields())
    a = Test01()
    for c in a.__table__.columns:
        print(c.name)
